<template>
  <div class="app-container">
    <div class="page-header">
      <h2 class="page-title">新建训练任务</h2>
    </div>

    <el-form
      ref="taskForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="task-form"
    >
      <!-- 基本任务配置 -->
      <div class="form-section">
        <h3 class="section-title">基本任务配置</h3>

        <!-- 任务名称 -->
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>

        <!-- 算法选择 -->
        <el-form-item label="算法选择" prop="algorithmId">
          <el-select
            v-model="form.algorithmId"
            placeholder="请选择算法"
            style="width: 100%"
            @change="handleAlgorithmChange"
          >
            <el-option
              v-for="item in algorithmOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 项目选择 -->
        <el-form-item label="项目选择" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目" />
        </el-form-item>

        <!-- 场景选择 -->
        <el-form-item label="场景选择" prop="sceneId">
          <el-input v-model="form.sceneId" placeholder="请输入场景" />
        </el-form-item>

        <!-- 版本选择 -->
        <el-form-item label="版本选择" prop="versionId">
          <el-input v-model="form.versionId" placeholder="请输入版本" />
        </el-form-item>

        <!-- 任务描述 -->
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入任务描述"
          />
        </el-form-item>
      </div>

      <!-- 数据配置 -->
      <div class="form-section">
        <h3 class="section-title">数据配置</h3>

        <!-- 环境选择 -->
        <el-form-item label="环境选择" prop="envSelection">
          <el-select
            v-model="form.envSelection"
            placeholder="请选择环境"
            style="width: 100%"
            @change="handleEnvSelectionChange"
          >
            <el-option
              v-for="item in envSelectionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- API方法 -->
        <el-form-item label="API方法" prop="apiMethod">
          <el-select
            v-model="form.apiMethod"
            placeholder="请选择API方法"
            style="width: 100%"
          >
            <el-option
              v-for="item in apiMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- API Host -->
        <el-form-item label="API Host" prop="apiHost">
          <el-input v-model="form.apiHost" placeholder="请输入API Host" />
        </el-form-item>

        <!-- API路径 -->
        <el-form-item label="API路径" prop="apiDataPath">
          <el-input v-model="form.apiDataPath" placeholder="请输入API路径" />
        </el-form-item>

        <!-- 请求类 -->
        <el-form-item label="请求类" prop="dataRequestClass">
          <el-input
            v-model="form.dataRequestClass"
            placeholder="请输入请求类"
          />
        </el-form-item>

        <!-- 响应类 -->
        <el-form-item label="响应类" prop="dataResponseClass">
          <el-input
            v-model="form.dataResponseClass"
            placeholder="请输入响应类"
          />
        </el-form-item>
      </div>

      <!-- 表单操作按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="submitForm">创建任务</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup name="TrainingCreate">
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import { createTrainingTask, getAlgorithmList } from "@/api/training";
import { getAlgorithm } from "@/api/algorithm";

const router = useRouter();
const { proxy } = getCurrentInstance();
const taskForm = ref(null);

// 存储当前选择的算法详情，用于环境切换时回显
const currentAlgorithmDetail = ref(null);

// 表单数据
const form = reactive({
  taskName: "",
  projectId: "",
  sceneId: "",
  algorithmId: "",
  versionId: "",
  description: "",
  envSelection: "",
  apiMethod: "",
  apiHost: "",
  apiDataPath: "",
  dataRequestClass: "",
  dataResponseClass: "",
});

// 表单校验规则
const rules = {
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  projectId: [{ required: true, message: "请输入项目", trigger: "blur" }],
  sceneId: [{ required: true, message: "请输入场景", trigger: "blur" }],
  algorithmId: [{ required: true, message: "请选择算法", trigger: "change" }],
  versionId: [{ required: true, message: "请输入版本", trigger: "blur" }],
};

// 选项数据
const projectOptions = ref([]);
const sceneOptions = ref([]);
const algorithmOptions = ref([]);
const versionOptions = ref([]);

const envSelectionOptions = ref([
  { value: "testing", label: "测试环境" },
  { value: "production", label: "生产环境" },
]);

const apiMethodOptions = ref([
  { value: "GET", label: "GET" },
  { value: "POST", label: "POST" },
  { value: "PUT", label: "PUT" },
  { value: "DELETE", label: "DELETE" },
]);

// 根据环境选择回显 API 配置
function fillApiConfigFromEnv(apiEnv) {
  if (!apiEnv) {
    return;
  }

  // 回显 API 相关字段
  form.apiMethod = apiEnv.api_method || "";
  form.apiHost = apiEnv.api_host || "";
  form.apiDataPath = apiEnv.api_path || "";
  form.dataRequestClass = apiEnv.request_class || "";
  form.dataResponseClass = apiEnv.response_class || "";
}

// 处理环境选择变更
function handleEnvSelectionChange(envValue) {
  if (!currentAlgorithmDetail.value || !currentAlgorithmDetail.value.dev_env) {
    return;
  }

  const devEnv = currentAlgorithmDetail.value.dev_env;
  let apiEnv = null;

  if (envValue === "testing" && devEnv.testing_env) {
    apiEnv = devEnv.testing_env;
  } else if (envValue === "production" && devEnv.production_env) {
    apiEnv = devEnv.production_env;
  }

  if (apiEnv) {
    fillApiConfigFromEnv(apiEnv);
  } else {
    // 如果选择的环境没有数据，清空字段
    form.apiMethod = "";
    form.apiHost = "";
    form.apiDataPath = "";
    form.dataRequestClass = "";
    form.dataResponseClass = "";
  }
}

// 处理算法选择变更
async function handleAlgorithmChange(algorithmId) {
  if (!algorithmId) {
    currentAlgorithmDetail.value = null;
    return;
  }

  try {
    const response = await getAlgorithm(algorithmId);
    currentAlgorithmDetail.value = response;
    const algorithmDetail = response;

    // 回显基本任务配置字段（字段直接在顶层，不在 algo_info 中）
    form.projectId = algorithmDetail.project || "";
    form.sceneId = algorithmDetail.scenario || "";
    form.versionId = algorithmDetail.version || "";
    form.description = algorithmDetail.description || "";

    // 回显数据配置字段
    if (algorithmDetail.dev_env) {
      const devEnv = algorithmDetail.dev_env;

      // 优先使用测试环境，如果测试环境不存在则使用生产环境
      let apiEnv = null;
      if (devEnv.testing_env) {
        form.envSelection = "testing";
        apiEnv = devEnv.testing_env;
      } else if (devEnv.production_env) {
        form.envSelection = "production";
        apiEnv = devEnv.production_env;
      }

      if (apiEnv) {
        fillApiConfigFromEnv(apiEnv);
      }
    }

    ElMessage.success("算法信息已自动填充");
  } catch (error) {
    console.error("获取算法详情失败:", error);
    ElMessage.error("获取算法详情失败，请稍后重试");
    currentAlgorithmDetail.value = null;
  }
}

/** 获取算法列表 */
async function getAlgorithmOptions() {
  try {
    const response = await getAlgorithmList();
    // 处理不同的返回格式：可能是 { items: [], pagination: {} } 或直接数组
    const algorithms = response.items || response.data || response || [];
    algorithmOptions.value = algorithms.map((algorithm) => ({
      value: algorithm.file_id,
      label: algorithm.name,
    }));

    // 同时获取项目和场景选项
    const projects = [
      ...new Set(algorithms.map((a) => a.project).filter(Boolean)),
    ];
    const scenarios = [
      ...new Set(algorithms.map((a) => a.scenario).filter(Boolean)),
    ];

    projectOptions.value = projects.map((project) => ({
      value: project,
      label: project,
    }));

    sceneOptions.value = scenarios.map((scenario) => ({
      value: scenario,
      label: scenario,
    }));

    // 获取版本选项
    const versions = [
      ...new Set(algorithms.map((a) => a.version).filter(Boolean)),
    ];
    versionOptions.value = versions.map((version) => ({
      value: version,
      label: version,
    }));
  } catch (error) {
    console.error("获取算法列表失败:", error);
    ElMessage.error("获取算法列表失败");
  }
}

// 提交表单
async function submitForm() {
  try {
    const valid = await proxy.$refs["taskForm"].validate();
    if (!valid) return;

    const loading = ElLoading.service({
      lock: true,
      text: "正在创建任务...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 准备API数据
    const taskInfo = {
      task_name: form.taskName,
      project: form.projectId,
      scenario: form.sceneId,
      algorithm: form.algorithmId,
      version: form.versionId,
      description: form.description,
    };

    const apiInfo = {
      api_method: form.apiMethod || "POST",
      api_host: form.apiHost || "",
      api_path: form.apiDataPath || "/api/training",
      api_headers: { "Content-Type": "application/json" },
      api_params: { dataset: "test_data" },
      request_class: form.dataRequestClass || null,
      response_class: form.dataResponseClass || null,
    };

    const requestData = {
      task_info: taskInfo,
      api_info: apiInfo,
    };

    await createTrainingTask(requestData);
    loading.close();
    ElMessage.success("创建任务成功");
    router.push("/model/training");
  } catch (error) {
    console.error("创建任务失败:", error);
    ElMessage.error("创建任务失败: " + (error.message || "未知错误"));
  }
}

// 取消
function cancel() {
  router.push("/model/training");
}

// 初始化数据
onMounted(async () => {
  try {
    await getAlgorithmOptions();
  } catch (error) {
    console.error("初始化数据失败:", error);
    ElMessage.error("初始化数据失败");
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.task-form {
  max-width: 800px;
  margin: 0 auto;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>
